package com.macro.mall.demo.service.impl;



import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.dto.AddressData;
import com.macro.mall.common.dto.IndexDto;
import com.macro.mall.demo.service.EsIndexService;
import com.macro.mall.demo.uilt.Mangers;
import com.macro.mall.mapper.EsMapper;
import com.macro.mall.model.OrderInfo;

import com.macro.mall.model.PmsProduct;
import com.macro.mall.model.UmsMemberReceiveAddress;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class EsIndexServiceImpl implements EsIndexService {
    private static final String ES_INDEX = "mall";
    @Autowired
    private EsMapper mapper;

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private Mangers mangers;

    /**
     * 创建 索引
     */
    @Override
    public void foundIndex(IndexDto indexDto) {

        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexDto.getIndexName());

        CommonResult exists = exists(indexDto.getIndexName());
        Object data = exists.getData();
        if (data.equals(true)) {
            throw new RuntimeException("已存在！");
        }
        if (indexDto.getSettings() != null) {
            createIndexRequest.settings(indexDto.getSettings(), XContentType.JSON);
        }
        if (indexDto.getMappings() != null) {
            createIndexRequest.mapping(indexDto.getMappings(), XContentType.JSON);
        }

        try {
            client.indices().create(createIndexRequest, RequestOptions.DEFAULT);


        } catch (IOException e) {
            log.error("创建索引失败:" + e.getMessage());
            throw new RuntimeException("创建索引失败");
        }

    }

    /**
     * 删除索引
     */
    @Override
    public void delIdnex(IndexDto indexDto) {
        try {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexDto.getIndexName());
            client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除索引失败:" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改 索引
     */
    @Override
    public void updIndex(IndexDto indexDto) {
        try {
            CommonResult exists = exists(indexDto.getIndexName());
            Object data = exists.getData();
            if (data.equals(false)) {
                throw new RuntimeException("不已存在！");
            }
            PutMappingRequest putMappingRequest = new PutMappingRequest(indexDto.getIndexName());
            client.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("修改索引失败:" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询 索引
     */
    @Override
    public Map<String, Object> selIndex(IndexDto indexDto) {
        Map<String, Object> map = new HashMap<>();
        try {
            SearchRequest searchRequest = new SearchRequest(indexDto.getIndexName());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //条件
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchRequest.source(searchSourceBuilder);

            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            map.put("name", search);
        } catch (IOException e) {
            log.error("查询失败:" + e.getMessage());
            throw new RuntimeException(e);
        }


        return map;
    }

    /**
     * 判断索引 是否存在
     */
    @Override
    public CommonResult exists(String indexName) {
        Boolean getIndexResponse = false;
        try {
            GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);

            getIndexResponse = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            if (getIndexResponse) {
                return CommonResult.success(true);
            } else {
                return CommonResult.success(false);
            }

        } catch (IOException e) {
            // 其他IO异常
            log.error("检查索引是否存在时发生IO异常", e);
            throw new RuntimeException("检查索引是否存在时发生IO异常", e);
        }


    }


    /**
     * 上架
     */
    @Override
    public void putaway(List<Long> ids) {
        try {
        //查询 商品数据
        List<PmsProduct> pmsProducts = mapper.selMall(ids);

            //添加es
        BulkRequest bulkRequest = new BulkRequest();
        ids.forEach(id->{
            pmsProducts.forEach(product -> {
                bulkRequest.add(new IndexRequest(ES_INDEX).id(id+"")
                        .source(JSONObject.toJSONString(product), XContentType.JSON));
            });
        });
            client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 下架
     */
    @Override
    public void soldOut(List<Long> ids) {
        try {
        BulkRequest bulkRequest = new BulkRequest();
        ids.forEach(id->{
            bulkRequest.add(new DeleteRequest(ES_INDEX, id+""));
        });
            client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("下架失败");
        }
    }



}



